package servletlearn.reqres;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet(name = "ReqMVCServlet", urlPatterns = "/rmServlet")
public class ReqMVCServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*String data = "中国";
        request.setAttribute("data", data);
        request.getRequestDispatcher("/message.jsp")
                .forward(request, response);*/
        /*response.setContentType("text/html;charset=utf-8");
        request.getRequestDispatcher("/public/head.jsp").include(request, response);
        response.getWriter().write("数据<br>");
        request.getRequestDispatcher("public/foot.jsp").include(request, response);*/


        response.setCharacterEncoding("utf-8");//防止乱码,默认查iso8859-1
        response.setContentType("text/html;charset=utf-8");
        response.addHeader("content-type", "text/html;charset=utf-8");//控制浏览器
        response.setDateHeader("expires", 1000 * 120 + System.currentTimeMillis());
        PrintWriter writer = response.getWriter();

        Map<String, String[]> params = request.getParameterMap();
        String queryString = "返回：&";
        if (params != null) {
            System.out.println("params:" + params.size());
            for (String key : params.keySet()) {
                String[] values = params.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value = values[i];
                    queryString += key + "=" + value + "&";
                }
            }
        } else {
            System.out.println("没有参数");
        }

        // 去掉最后一个空格
        queryString = queryString.substring(0, queryString.length() - 1);
        System.out.println("POST " + request.getRequestURL() + " " + queryString);
        writer.write("POST " + request.getRequestURL() + " " + queryString);
        writer.close();
//        writer.println("POST " + request.getRequestURL() + " " + queryString);
    }


}
